const http = require('http')
const mysql = require('mysql')

let server = http.createServer(function (request, response) {
    //1.接收请求
    //解决跨域问题
    response.setHeader('Access-Control-Allow-Origin', '*')
    //解决中文乱码问题
    response.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8'
    })
    //2.处理业务逻辑
    let path = request.url
    if (path.indexOf('/api/productlist') !== -1) {
        //创建数据库连接对象
        let connect = mysql.createConnection({
            host: "localhost",
            user: "root",
            password: "123456",
            database: "yg_manager"

        })
        //打开数据库连接
        connect.connect()
        //执行sql 语句
        let sql = "SELECT * FROM y_product"
        connect.query(sql, function (err, data) {
            if (err) {
                console.log('数据库操作出错' + err)
                return
            }
            let dataStr=JSON.stringify(data)
            response.write(dataStr)
            response.end()
        })
        //关闭连接
        connect.end()
    }else{
        response.write('只支持/api/productlist接口')
        response.end()
    }
})
server.listen(3000,()=>{
    console.log('启动成功，监听端口为3000...')
})